﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using Microsoft.Practices.Unity;
using MiniStock.Entities.Common.Events;
using MiniStock.BusinessLogic.EventDispatcher;
using MiniStock.Infrastructure;
using MiniStock.Entities.Common;

namespace MiniStock.ServiceFacade
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class ServiceFacade: IServiceFacade
    {
        private EventDispatcherLogic _dispatcherLogic = null;
        EventDispatcherLogic DispatcherLogic { 
            get
            {
                if (_dispatcherLogic == null)
                {
                    lock (this)
                    {
                        if(_dispatcherLogic == null) 
                            _dispatcherLogic = MiniStockContext.Current.RootContainer.Resolve<EventDispatcherLogic>();
                    }
                }

                return _dispatcherLogic;
            }
        }

        private EntityQueryLogic _queryLogic = null;
        EntityQueryLogic QueryLogic
        {
            get
            {
                if (_queryLogic == null)
                {
                    lock (this)
                    {
                        if (_queryLogic == null)
                            _queryLogic = MiniStockContext.Current.RootContainer.Resolve<EntityQueryLogic>();
                    }
                }

                return _queryLogic;
            }
        }

        #region IServiceFacade Members

        public Guid SubmitEvent(EntityEventBase arg)
        {
            using (var c = new MiniStockContextScope())
            {
                return DispatcherLogic.SubmitEvent(arg);
            }
        }

        public StatusQueryEvent GetResult(Guid correlationId)
        {
            using (var c = new MiniStockContextScope())
            {
                return DispatcherLogic.GetResult(correlationId);
            }
        }

        public EntityBase GetEntity(string hash)
        {
            using(var c = new MiniStockContextScope())
            {
                return QueryLogic.GetEntityByHash(hash);
            }
        }

        public List<EntityBase> ListEntity(string entity, Dictionary<string, string> filter)
        {
            using (var c = new MiniStockContextScope())
            {
                return QueryLogic.ListEntity(entity, filter);
            }
            
        } 

        #endregion
    }
}
